package cn.yuanqiao.web.controller.archive.danganzhengli;

import cn.yuanqiao.archive.appManager.service.ITenantSysConfigService;
import cn.yuanqiao.archive.danganzhengli.domain.YqdaOnlineReception;
import cn.yuanqiao.archive.danganzhengli.service.IOnlineReceptionService;
import cn.yuanqiao.archive.detection.service.IDetectionObjectService;
import cn.yuanqiao.common.core.domain.R;
import cn.yuanqiao.common.core.domain.model.LoginUser;
import cn.yuanqiao.common.utils.poi.ExcelUtil;
import cn.yuanqiao.common.web.controller.BaseController;
import cn.yuanqiao.common.core.domain.AjaxResult;
import cn.yuanqiao.common.web.page.TableDataInfo;
import cn.yuanqiao.common.annotation.Log;
import cn.yuanqiao.common.enums.BusinessType;
import cn.yuanqiao.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.file.Paths;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/archive/onlineReception")
public class OnlineReceptionController extends BaseController {

    @Autowired
    private IOnlineReceptionService onlineReceptionService;
    @Autowired
    private ITenantSysConfigService sysConfigService;
    @Autowired
    private IDetectionObjectService detectionObjectService;

    @Log(title = "查询移交单列表", businessType = BusinessType.SELECT)
    @PostMapping("/getOnlineReceptionList")
    public TableDataInfo getOnlineReceptionList(YqdaOnlineReception onlineReception){
        String tenantcode = SecurityUtils.getTenantCode();
        //YqdaOnlineReception onlineReception = new YqdaOnlineReception();
        onlineReception.setTenantCode(tenantcode);
        //onlineReception.setType(type);
        startPage();
        List<YqdaOnlineReception> list = onlineReceptionService.selectYqdaOnlineReceptionList(onlineReception);
        return getDataTable(list);
    }

    @Log(title = "查询单个移交单", businessType = BusinessType.SELECT)
    @GetMapping("/getOnlineReceptionById")
    public AjaxResult getOnlineReceptionById(@RequestParam("id")Long id){
        //String tenantcode = SecurityUtils.getTenantCode();
        //YqdaOnlineReception onlineReception = new YqdaOnlineReception();
        //onlineReception.setTenantCode(tenantcode);
        //onlineReception.setType(type);
        YqdaOnlineReception onlineReception = onlineReceptionService.getOnlineReceptionById(id);
        return AjaxResult.success(onlineReception);
    }

    @Log(title = "离线接收导入", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception
    {
        ExcelUtil<YqdaOnlineReception> util = new ExcelUtil<>(YqdaOnlineReception.class);
        List<YqdaOnlineReception> list = util.importExcel(file.getInputStream());
        if(list!=null && list.size()==1){
            YqdaOnlineReception onlineReception = list.get(0);
            LoginUser user = SecurityUtils.getLoginUser();
            onlineReception.setTenantCode(user.getTenantCode());
            onlineReception.setCreateBy(user.getUsername());
            onlineReception.setCreateId(user.getUserId());
            onlineReception.setReceptionTime(new Date());
            onlineReception.setState(0);
            onlineReception.setTenantCode(SecurityUtils.getTenantCode());
            onlineReceptionService.insertOnlineReception(onlineReception);
            return AjaxResult.success(onlineReception);
        }else {
            return AjaxResult.error("导入失败");
        }
    }

    @Log(title = "移交包导入", businessType = BusinessType.IMPORT)
    @PostMapping("/savePackage")
    public AjaxResult savePackage(MultipartFile file,Long id) throws Exception
    {
        String path = sysConfigService.selectConfigByKey("MNT_Package");
        File desc = new File(path + File.separator + (new Date().getTime())+".zip");
        if (!desc.exists())
        {
            if (!desc.getParentFile().exists())
            {
                desc.getParentFile().mkdirs();
            }
        }
        File savePath = desc.isAbsolute() ? desc : desc.getAbsoluteFile();
        file.transferTo(Paths.get(savePath.getAbsolutePath()));
        logger.info(Paths.get(savePath.getAbsolutePath()).toString());
        YqdaOnlineReception onlineReception = new YqdaOnlineReception();
        onlineReception.setId(id);
        onlineReception.setFilePath(Paths.get(savePath.getAbsolutePath()).toString());
        onlineReceptionService.updateYqdaOnlineReception(onlineReception);
        //JSONObject msg = onlineReceptionService.saveArchivePackage(savePath,id,SecurityUtils.getTenantCode());
        return AjaxResult.success();
    }


    //接收移交包,登记审批
    @Log(title = "移交包接收审批", businessType = BusinessType.SUBMIT)
    @PostMapping("/fqjssp")
    public AjaxResult fqjssp(@RequestParam("ids") Long [] ids){
        return AjaxResult.success(onlineReceptionService.fqjssp(ids));
    }


    @Log(title = "在线接收办结", businessType = BusinessType.UPDATE)
    @PostMapping("/onlinereceiveBanjie/{id}")
    public R<Integer> onlinereceiveBanjie(@PathVariable("id") Long id) {
        int i = onlineReceptionService.onlinereceiveBanjie(id);
        onlineReceptionService.sendPackageState(id,"success");
        return R.ok(Integer.valueOf(i));
    }

    @Log(title = "在线接收审批流程不同意", businessType = BusinessType.UPDATE)
    @PostMapping("/killOnlineReceive/{id}")
    public AjaxResult killOnlineReceive(@PathVariable("id") Long id) {
        onlineReceptionService.killOnlineReceive(id);
        return AjaxResult.success();
    }

    @Log(title = "删除移交单", businessType = BusinessType.DELETE)
    @PostMapping("/deletePackage/{id}")
    public AjaxResult deletePackage(@PathVariable("id") Long id) {
        onlineReceptionService.deletePackage(id,-2);
        return AjaxResult.success();
    }

    @Log(title = "四性检测并且入库", businessType = BusinessType.SELECT)
    @GetMapping("/saveArchive")
    public AjaxResult getOnlineReceptionById(@RequestParam("id")Long id,@RequestParam("categoryId")Long categoryId,@RequestParam("code")String code,@RequestParam("link")String link) throws Exception{
        YqdaOnlineReception onlineReception = onlineReceptionService.getOnlineReceptionById(id);
        String path=onlineReception.getFilePath();  //移交包路径
        //开始四性检测
        Map map= detectionObjectService.detectionPackage( path,  code, link,"1");
        //档案入库  入库状态 13
        Integer failNum=Integer.parseInt(map.get("failNum").toString());
        //onlineReceptionService.saveSiXingResult(id,Long.parseLong(map.get("sxId").toString()),failNum>0?"不通过":"通过");
        Map param=new HashMap();
        if(failNum>0){
            param.put("code","500");
            param.put("sxId",map.get("sxId").toString());
            onlineReceptionService.saveSiXingResult(id,Long.parseLong(map.get("sxId").toString()),"不通过");
            return AjaxResult.success(param);
        }else {
            param.put("code","200");
            param.put("sxId",map.get("sxId").toString());
            try {
                //解析包的档案入库
                onlineReceptionService.saveArchivePackage(new File(onlineReception.getFilePath()), id, categoryId, SecurityUtils.getTenantCode());
                //更新状态
                onlineReceptionService.saveSiXingResult(id,Long.parseLong(map.get("sxId").toString()),"通过");
            }catch (Exception e){
                logger.error(e.getMessage(),e);
                onlineReceptionService.saveSiXingResult(id,Long.parseLong(map.get("sxId").toString()),"不通过");
                return AjaxResult.error(e.getMessage());
            }
            return AjaxResult.success(param);
        }
    }

    @Log(title = "退回", businessType = BusinessType.UPDATE)
    @PostMapping("/sendBackOnline/{id}")
    public AjaxResult sendBackOnline(@PathVariable("id") Long id){
        onlineReceptionService.deletePackage(id,5);
        onlineReceptionService.sendPackageState(id,"fail");
        return AjaxResult.success();
    }


}
